<template>
  <div class="trend-analysis">
    <div class="header">
      <h2>热门话题与趋势分析</h2>
      <div class="controls">
        <select v-model="selectedCategory" @change="filterTopics">
          <option value="all">所有分类</option>
          <option v-for="category in categories" :key="category" :value="category">
            {{ category }}
          </option>
        </select>
        <button @click="refreshData" class="refresh-btn">
          <span class="icon">↻</span> 刷新
        </button>
        <div class="time-range">
          <span>时间范围：</span>
          <select v-model="selectedTimeRange" @change="updateChart">
            <option value="7">最近7天</option>
            <option value="14">最近14天</option>
            <option value="30">最近30天</option>
          </select>
        </div>
      </div>
    </div>

    <div class="content">
      <!-- 热门话题列表 -->
      <div class="hot-topics">
        <h3>热门话题排行榜</h3>
        <div class="topic-list">
          <div
              v-for="(topic, index) in filteredTopics"
              :key="topic.id"
              class="topic-item"
              :class="{ 'top-rank': index < 3 }"
              @click="selectTopic(topic)"
          >
            <div class="rank">{{ index + 1 }}</div>
            <div class="topic-info">
              <div class="title">{{ topic.title }}</div>
              <div class="meta">
                <span class="category">{{ topic.category }}</span>
                <span class="date">{{ formatDate(topic.createdAt) }}</span>
              </div>
              <div class="stats">
                <span class="votes">投票: {{ topic.voteCount.toLocaleString() }}</span>
                <span class="participants">参与: {{ topic.participants.toLocaleString() }}</span>
                <span class="trend" :class="getTrendClass(topic.trend)">
                  {{ getTrendIcon(topic.trend) }} {{ Math.abs(topic.trend) }}%
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 趋势图表和详情 -->
      <div class="trend-detail">
        <div v-if="selectedTopic" class="detail-card">
          <h3>{{ selectedTopic.title }}</h3>
          <div class="topic-meta">
            <span>分类: {{ selectedTopic.category }}</span>
            <span>创建时间: {{ formatDate(selectedTopic.createdAt) }}</span>
            <span>话题ID: {{ selectedTopic.id }}</span>
          </div>

          <div class="chart-container">
            <canvas ref="chartCanvas"></canvas>
          </div>

          <div class="summary-stats">
            <div class="stat-item">
              <div class="stat-value">{{ selectedTopic.voteCount.toLocaleString() }}</div>
              <div class="stat-label">总投票数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ selectedTopic.participants.toLocaleString() }}</div>
              <div class="stat-label">参与人数</div>
            </div>
            <div class="stat-item">
              <div class="stat-value" :class="getTrendClass(selectedTopic.trend)">
                {{ getTrendIcon(selectedTopic.trend) }} {{ Math.abs(selectedTopic.trend) }}%
              </div>
              <div class="stat-label">趋势变化</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ calculateEngagementRate(selectedTopic) }}%</div>
              <div class="stat-label">参与率</div>
            </div>
          </div>
        </div>
        <div v-else class="no-selection">
          <div class="placeholder-icon">📊</div>
          <p>点击左侧话题查看详细分析</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue';
import Chart from 'chart.js/auto';

export default {
  name: 'TrendAnalysis',
  setup() {
    // 数据状态
    const topics = ref([]);
    const filteredTopics = ref([]);
    const selectedTopic = ref(null);
    const selectedCategory = ref('all');
    const selectedTimeRange = ref('7');
    const categories = ref([]);
    const chartInstance = ref(null);

    // 生成模拟数据
    const generateMockData = () => {
      const mockCategories = ['科技', '社会', '教育', '娱乐', '健康', '财经', '体育'];
      const mockTopics = [];

      const now = new Date();

      for (let i = 0; i < 15; i++) {
        const daysAgo = Math.floor(Math.random() * 30);
        const createdAt = new Date(now);
        createdAt.setDate(now.getDate() - daysAgo);

        const baseVotes = Math.floor(Math.random() * 5000) + 500;
        const trendData = [];
        const timeRange = parseInt(selectedTimeRange.value);

        // 生成趋势数据
        let current = baseVotes / 2;
        for (let j = 0; j < timeRange; j++) {
          const increment = Math.floor(Math.random() * (baseVotes / 10)) + 10;
          current += increment;
          trendData.push(Math.floor(current));
        }

        // 计算趋势百分比 (最近两天的变化)
        const trend = trendData.length > 1
            ? Math.round(((trendData[trendData.length-1] - trendData[trendData.length-2]) / trendData[trendData.length-2]) * 100)
            : 0;

        const category = mockCategories[Math.floor(Math.random() * mockCategories.length)];

        mockTopics.push({
          id: `topic-${i+1}`,
          title: getRandomTitle(category),
          category,
          voteCount: trendData[trendData.length-1],
          participants: Math.floor(trendData[trendData.length-1] * (0.7 + Math.random() * 0.3)),
          trend,
          trendData,
          createdAt
        });
      }

      // 按投票数排序
      return mockTopics.sort((a, b) => b.voteCount - a.voteCount);
    };

    // 生成随机话题标题
    const getRandomTitle = (category) => {
      const titles = {
        '科技': [
          '人工智能对未来就业的影响',
          '5G技术的应用前景分析',
          '元宇宙概念的实际价值探讨',
          '量子计算的发展现状调查',
          '区块链技术的非金融应用'
        ],
        '社会': [
          '城市垃圾分类实施效果评估',
          '共享单车管理的优化方案',
          '社区养老服务的需求调查',
          '夜间经济发展趋势分析',
          '城市交通拥堵解决方案'
        ],
        '教育': [
          '在线教育的优势与局限性',
          '双减政策实施后的效果评估',
          '职业教育的发展方向探讨',
          '青少年心理健康教育需求',
          '高校专业设置与社会需求匹配度'
        ],
        '娱乐': [
          '短视频对文化传播的影响',
          '国产影视剧质量提升分析',
          '电子竞技的规范化发展',
          '明星效应对社会价值观的影响',
          '网络直播行业的监管建议'
        ],
        '健康': [
          '全民健身计划实施效果',
          '心理健康服务的普及需求',
          '中医药发展的现状与未来',
          '医患关系改善的有效途径',
          '健康饮食观念的普及情况'
        ],
        '财经': [
          '数字货币的发展趋势',
          '小微企业融资难题解决方案',
          '个人理财观念的现状调查',
          '房地产市场的未来走向',
          '消费升级对经济的影响'
        ],
        '体育': [
          '全民健身与体育产业发展',
          '校园体育设施的完善需求',
          '电子竞技进入奥运会的可行性',
          '体育明星的商业价值分析',
          '大型体育赛事对城市发展的影响'
        ]
      };

      const categoryTitles = titles[category] || titles['科技'];
      return categoryTitles[Math.floor(Math.random() * categoryTitles.length)];
    };

    // 初始化数据
    const loadData = () => {
      const data = generateMockData();
      topics.value = data;
      filteredTopics.value = [...data];

      // 提取分类
      const uniqueCategories = [...new Set(data.map(topic => topic.category))];
      categories.value = uniqueCategories;
    };

    // 刷新数据
    const refreshData = () => {
      loadData();
      if (selectedTopic.value) {
        // 重新选择当前话题以更新图表
        const topic = topics.value.find(t => t.id === selectedTopic.value.id);
        if (topic) selectTopic(topic);
      }
    };

    // 按分类筛选话题
    const filterTopics = () => {
      if (selectedCategory.value === 'all') {
        filteredTopics.value = [...topics.value];
      } else {
        filteredTopics.value = topics.value.filter(topic => topic.category === selectedCategory.value);
      }
    };

    // 选择话题显示趋势图
    const selectTopic = (topic) => {
      selectedTopic.value = topic;
    };

    // 更新时间范围
    const updateChart = () => {
      if (selectedTopic.value) {
        // 重新生成数据时保持选择相同ID的话题
        const topicId = selectedTopic.value.id;
        loadData();
        const topic = topics.value.find(t => t.id === topicId);
        if (topic) selectTopic(topic);
      } else {
        loadData();
      }
    };

    // 获取趋势图标
    const getTrendIcon = (trend) => {
      if (trend > 0) return '↑';
      if (trend < 0) return '↓';
      return '→';
    };

    // 获取趋势样式类
    const getTrendClass = (trend) => {
      if (trend > 5) return 'up';
      if (trend < -5) return 'down';
      return 'neutral';
    };

    // 格式化日期
    const formatDate = (date) => {
      return new Date(date).toLocaleDateString('zh-CN');
    };

    // 计算参与率
    const calculateEngagementRate = (topic) => {
      return Math.round((topic.participants / topic.voteCount) * 100);
    };

    // 初始化图表
    const initChart = (canvas, topic) => {
      if (chartInstance.value) {
        chartInstance.value.destroy();
      }

      const timeRange = parseInt(selectedTimeRange.value);
      const labels = [];
      for (let i = timeRange; i > 0; i--) {
        labels.push(`${i}天前`);
      }
      labels[labels.length-1] = '今天';

      const ctx = canvas.getContext('2d');
      chartInstance.value = new Chart(ctx, {
        type: 'line',
        data: {
          labels: labels,
          datasets: [{
            label: '投票数量',
            data: topic.trendData,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.3,
            fill: true,
            backgroundColor: 'rgba(75, 192, 192, 0.1)',
            pointBackgroundColor: 'rgb(75, 192, 192)',
            pointRadius: 4,
            pointHoverRadius: 6
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false
            },
            tooltip: {
              mode: 'index',
              intersect: false,
              callbacks: {
                label: function(context) {
                  return `投票数: ${context.parsed.y.toLocaleString()}`;
                }
              }
            }
          },
          scales: {
            y: {
              beginAtZero: false,
              ticks: {
                callback: function(value) {
                  return value.toLocaleString();
                }
              }
            }
          }
        }
      });
    };

    // 生命周期钩子
    onMounted(() => {
      loadData();
    });

    // 监听选中的话题变化
    watch(selectedTopic, (newTopic) => {
      if (newTopic && chartCanvas.value) {
        initChart(chartCanvas.value, newTopic);
      }
    });

    const chartCanvas = ref(null);

    return {
      topics,
      filteredTopics,
      selectedTopic,
      selectedCategory,
      selectedTimeRange,
      categories,
      chartCanvas,
      filterTopics,
      refreshData,
      selectTopic,
      updateChart,
      getTrendIcon,
      getTrendClass,
      formatDate,
      calculateEngagementRate
    };
  }
};
</script>

<style scoped>
.trend-analysis {
  font-family: 'Arial', sans-serif;
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.header h2 {
  color: #2c3e50;
  margin: 0;
  font-size: 1.8rem;
}

.controls {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 15px;
}

select {
  padding: 8px 15px;
  border-radius: 6px;
  border: 1px solid #ddd;
  background-color: white;
  font-size: 0.9rem;
  cursor: pointer;
}

.refresh-btn {
  padding: 8px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.refresh-btn:hover {
  background-color: #3aa876;
}

.icon {
  font-size: 14px;
}

.time-range {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
}

.content {
  display: grid;
  grid-template-columns: 1fr 1.5fr;
  gap: 25px;
}

.hot-topics {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
}

.hot-topics h3 {
  margin-top: 0;
  color: #34495e;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
  font-size: 1.2rem;
}

.topic-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.topic-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  background-color: #f5f5f5;
  cursor: pointer;
  transition: all 0.2s;
  border-left: 4px solid transparent;
}

.topic-item:hover {
  background-color: #ebebeb;
  transform: translateX(3px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.topic-item.top-rank {
  background-color: #e8f4fc;
  border-left-color: #42b983;
}

.topic-item.top-rank:hover {
  background-color: #d4e9fa;
}

.rank {
  font-size: 1.1rem;
  font-weight: bold;
  color: #7f8c8d;
  min-width: 30px;
  text-align: center;
}

.topic-item.top-rank .rank {
  color: #42b983;
  font-size: 1.2rem;
}

.topic-info {
  flex: 1;
}

.title {
  font-weight: 600;
  margin-bottom: 6px;
  color: #2c3e50;
  font-size: 1rem;
}

.meta {
  display: flex;
  gap: 10px;
  font-size: 0.8rem;
  color: #7f8c8d;
  margin-bottom: 8px;
}

.stats {
  display: flex;
  gap: 15px;
  font-size: 0.85rem;
  color: #555;
}

.trend {
  margin-left: auto;
  font-weight: 600;
}

.trend.up {
  color: #42b983;
}

.trend.down {
  color: #e74c3c;
}

.trend.neutral {
  color: #f39c12;
}

.trend-detail {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  min-height: 500px;
}

.detail-card {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.detail-card h3 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 1.3rem;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.topic-meta {
  display: flex;
  gap: 15px;
  font-size: 0.85rem;
  color: #7f8c8d;
  margin: 10px 0;
  flex-wrap: wrap;
}

.chart-container {
  height: 300px;
  position: relative;
  margin: 20px 0;
}

.summary-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  margin-top: 20px;
}

.stat-item {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.stat-value {
  font-size: 1.5rem;
  font-weight: bold;
  margin-bottom: 5px;
  color: #2c3e50;
}

.stat-value.up {
  color: #42b983;
}

.stat-value.down {
  color: #e74c3c;
}

.stat-value.neutral {
  color: #f39c12;
}

.stat-label {
  font-size: 0.85rem;
  color: #7f8c8d;
}

.no-selection {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #95a5a6;
}

.placeholder-icon {
  font-size: 3rem;
  margin-bottom: 15px;
  opacity: 0.5;
}

.no-selection p {
  margin: 0;
  font-size: 1.1rem;
}

@media (max-width: 992px) {
  .content {
    grid-template-columns: 1fr;
  }

  .summary-stats {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 576px) {
  .header {
    flex-direction: column;
    align-items: flex-start;
  }

  .controls {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }

  .summary-stats {
    grid-template-columns: 1fr;
  }

  .stats {
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>